package com.dongan.service.impl;

import com.alibaba.druid.util.StringUtils;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.dongan.mapper.UserRoleMapper;
import com.dongan.mapper.UsersMapper;
import com.dongan.pojo.*;
import com.dongan.service.UsersService;
import com.dongan.utils.CommonProp;
import com.dongan.utils.JwtUtils;
import com.dongan.utils.ResultResponseUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Random;

/**
 * <p>
 * 用户表 服务实现类
 * </p>
 *
 * @author longTao
 * @since 2021-06-15
 */
@Service
public class UsersServiceImpl extends ServiceImpl<UsersMapper, Users> implements UsersService {

    @Autowired
    private UsersMapper usersMapper;
    @Autowired
    private UserRoleMapper userRoleMapper;
    @Override
    @Transactional
    public UsersRoleMenu queryById(Long id) {
        UsersRoleMenu usersRoleMenu = new UsersRoleMenu();
        List<Roles> list = usersMapper.queryRoleList(id);
        if (list != null&&!list.isEmpty()&&list.size()>0){
            usersRoleMenu.setRoleList(list);
            //菜单
            List<Menus> menusList=usersMapper.queryMenusList(list);
            //由于list集合来查询的菜单,可能会有重复,所以我们需要转出Set集合来进行去重,在来转成List
            HashSet<Menus> hashSet=new HashSet<Menus>(menusList);
            List<Menus> menus = recursiveQueryMenu(new ArrayList<>(hashSet));
            if (menus != null&&!list.isEmpty()&&list.size()>0) {
                usersRoleMenu.setMenusList(menus);
            }
            //权限
            List<Permission> queryPermissionList = usersMapper.queryPermissionList(list);
            HashSet<Permission> permissions=new HashSet<>(queryPermissionList);
            List<Permission> permissionList=queryPermissionByList(new ArrayList<>(permissions));
            if (permissionList!=null&&!list.isEmpty()&&list.size()>0){
                usersRoleMenu.setPermissionList(permissionList);
            }
        }
        return usersRoleMenu;
    }

    /**
     * 根据
     * 账号发送验证码
     *
     * @param account
     * @return
     */
    @Autowired
    private JavaMailSender javaMailSender;
    @Value("${spring.mail.username}")
    private String from;

    /**
     * 邮件发送
     * @param account
     * @return
     */
    @Async//开启异步请求
    @Override
    public ResultResponseUtil sendTheVerificationCode(String account) {
        //获取随机数
        Random random = new Random();
        String str="";
        for (int i=0;i<5;i++){
            str=str+random.nextInt(9);
        }
        CommonProp.verificationCode=str;
        try {
            SimpleMailMessage message = new SimpleMailMessage();
            message.setFrom(from);
            System.out.println(from);
            message.setTo(account);
            System.out.println("account = " + account);
            message.setSubject("东安市ERP管理系统验证码:");
            message.setText(str);
            javaMailSender.send(message);
            return new ResultResponseUtil(true,str);
        }catch (Exception e){
            return new ResultResponseUtil(false,str);
        }
    }

    /**
     * 删除之后,应该删除它与角色之间的关系
     * @param id
     * @return
     */
    @Transactional
    @Override
    public Boolean deleteUserById(Long id) {
        int i = usersMapper.deleteById(id);
        QueryWrapper<UserRole> queryWrapper=new QueryWrapper<>();
        queryWrapper.eq("USER_ID",id);
        int delete = userRoleMapper.delete(queryWrapper);
        return i>0&&delete>0?true:false;
    }

    /**
     * 登录方法
     * @param users
     * @return
     */
    @Override
    public String login(Users users) {
        //邮箱和密码非空判断
        if(StringUtils.isEmpty(users.getEmail())||StringUtils.isEmpty(users.getPassword())){
            return null;
        }
        //判断邮箱是否正确
        QueryWrapper<Users> queryWrapper=new QueryWrapper<>();
        queryWrapper.eq("email",users.getEmail());
        Users one = this.getOne(queryWrapper);
        //判断one是否为空
        if (null==one){
            return null;
        }
        //判断密码
        if (!users.getPassword().equals(one.getPassword())){
            return null;
        }

        //到这里表示登录成功!
        String jwtToken = JwtUtils.getJwtToken(one.getId().toString(),one.getEmail());
        //返回jwtToken字符串
        return jwtToken;
    }


    /**
     * 递归查询二级菜单
     *
     * @param list
     * @return
     */
    public List<Menus> recursiveQueryMenu(List<Menus> list) {
        List<Menus> menusList = new ArrayList<>();
        for (Menus menus : list) {
            if (menus.getParentId().longValue() == 0) {
                menusList.add(queryMenusList(list, menus));
            }
        }
        return menusList;
    }

    /**
     * 递归查询所有的二级菜单
     *
     * @param list
     * @param menus
     * @return
     */
    public Menus queryMenusList(List<Menus> list, Menus menus) {
        for (Menus m : list) {
            if (menus.getId().longValue() == m.getParentId().longValue()) {
                if (menus.getList() == null) {
                    menus.setList(new ArrayList<>());
                }
                menus.getList().add(queryMenusList(list, m));
            }
        }
        return menus;
    }


    /**
     * 根据list来递归查询
     *
     * @param list
     * @return
     */
    public List<Permission> queryPermissionByList(List<Permission> list) {
        List<Permission> list1 = new ArrayList<>();
        for (Permission permission : list) {
            if (permission.getPId().longValue() == 0) {
                list1.add(queryPermissionByPermission(list, permission));
            }
        }
        return list1;
    }

    /**
     * 根据list集合和对象依次进行判断
     *
     * @param list
     * @param permission
     * @return
     */
    public Permission queryPermissionByPermission(List<Permission> list, Permission permission) {
        for (Permission p : list) {
            if (p.getPId().longValue() == permission.getId().longValue()) {
                if (permission.getList() == null) {
                    permission.setList(new ArrayList<>());
                }
                permission.getList().add(queryPermissionByPermission(list, p));
            }
        }
        return permission;
    }
}
